package com.mybatis.resultset;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author luoc
 * @version 1.0
 * @date 2021/2/20 14:36
 * @since 1.0
 */
public class DefaultResultSetHandler implements ResultSetHandler {

    public <E> void handlerResultSet(ResultSet resultSet, List<E> ret, String className) {
        Class<E> clazz = null;
        try {
            clazz= (Class<E>) Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // 遍历resultSet
        while (true){
            try {
                if (!resultSet.next()) break;
                Object entity = clazz.newInstance();
                Field[] fields = clazz.getDeclaredFields();
                for (Field field: fields) {
                    field.setAccessible(true);
                    String fname = field.getName();
                    Type type = field.getGenericType();

                    if ("class java.lang.String".equals(type.toString())){
                        String cloumn  = resultSet.getString(fname);
                        field.set(entity,cloumn);
                    }else if ("class java.lang.Long".equals(type.toString())){
                        Long column = resultSet.getLong(fname);
                        field.set(entity, column);
                    } else if ("int".equals(type.toString())){
                        Long column = resultSet.getLong(fname);
                        field.set(entity, column);
                    }
                }
                ret.add((E) entity);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }

        }
    }
}
